package com.haojii.helloworld;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

public class MD5HashUtils {

	public static byte[] string2MD5HashByteArray(String input)
	{
		byte[] hash = null;
		try {
			hash = MessageDigest.getInstance("MD5").digest(input.getBytes());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hash;
	}
	
	public static String byteArray2Hex(byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }
	
	/**
	 * Gravatar URL:
	 * 
	 * "http://www.gravatar.com/avatar/"+( email->md5hash->hex )+"?d=monsterid";
	 * 
	 * @param email
	 * @return
	 */
	public static String getGravatarURL(String email)
	{
		StringBuilder sb = new StringBuilder();
		sb.append("http://www.gravatar.com/avatar/");
		sb.append(byteArray2Hex(string2MD5HashByteArray(email)));
		sb.append("?d=monsterid");
		return sb.toString();
	}

}
